<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.common>
// +----------------------------------------------------------------------

// 应用公共文件
use think\Db;
use think\Exception;
use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;

/*支付服务器处理逻辑*/

function Db_connect_server_pay_domian($order_id,$price,$time=''){

    // 如果是线上301测试渠道或者是内网
    return (new app\home\service\GameProcess($order_id,$price))->orderProcess();

    // $channel_id =Db::connect('db_config2')->table('tradelog')->where('id',$order_id)->value('channel_id');
    // if(env('IS_DEVELOP') == 1 || $channel_id == 301 || $channel_id == 537 || $channel_id == 545 || $channel_id == 26 || $channel_id == 30 || $channel_id == 3 || $channel_id == 652 || $channel_id == 586 || $channel_id == 525 || $channel_id == 547 || $channel_id == 541 || $channel_id == 585 || $channel_id == 546){
    // }else{
    //     return (new Notifyold())->order_notify_handle_old($order_id,$price,$time);
    // }
}

/**
 * 获取玩家当前所在服务器对应的计费点配置
 */
function getServerGoods($server_no,$goods_id){

    if(env('IS_DEVELOP') == 1){
        return Specific_parameters_commodities_server_B($goods_id);
    }

    switch ($server_no) {
        case '1':
            $config = Specific_parameters_commodities($goods_id);
            break;
        case '2':
        case '3':
        case '4':
            $config = Specific_parameters_commodities_server_B($goods_id);
            break;
        default:
            // 出现异常 可能原因：老玩家没有登录游戏就直接离线充值
            throw new Exception('LoginServer not found');
            break;
    }

    return $config;
}

/**
 * 根据服务器编号获取玩家当前所在服务器的接口url
 */
function getServerUrl($server_no){

    if(env('IS_DEVELOP') == 1){
        return config('HTTP_URL_TEST');;
    }

    switch ($server_no) {
        case '1':
            $url = config('HTTP_URL_FORMAL');
            break;
        case '2':
            $url = config('HTTP_URL_FORMAL_GROUP_B');
            break;
        case '3':
            $url = config('HTTP_URL_FORMAL_GROUP_C');
            break;
        case '4':
            $url = config('HTTP_URL_FORMAL_GROUP_D');
            break;
        default:
            // 出现异常 可能原因：老玩家没有登录游戏就直接离线充值
            throw new Exception('server_no not found');
            break;
    }

    return $url;
}

/**
 * 返回错误信息代码
 * @author chenhan
 * @access public
 * @param  mixed    $data           提示信息或是数组
 * @param  int      $returncolla    判断是否加密：1加密，0不加密
 * @return string   返回json数据
 **/
function puterror($data,$returncolla=0){
    //用户需要看到的文字信息，手动加入$error数组
    //不需要的给数字：例如：puterror(100,$returncolla);
    //返回参数就是：'{"status": 0,"msg": "错误：100"}'
    $error = array(
        1       =>  '参数错误',
        2       =>  '未查到相关信息',
        3       =>  '操作失败',
        201       =>  '身份标识不存在',
        202       =>  '礼包已领取',
    );
    //成功时，输出data数组
    if(is_array($data)){
        $res['status']=0;
        $res=array_merge($res,$data);
    }else{
        $res['status']=0;
        if(is_numeric($data)){
            if(key_exists($data,$error)){
                $res['msg']=$error[$data];
            }else{
                $res['msg'] = '错误：'.$data;
            }
        }else{
            $res['msg']=$data;
        }
    }
    $return = json_encode($res,JSON_UNESCAPED_UNICODE);
    //判断是否需要加密
    if($returncolla == 1){
        $iv = config('AES_token.iv');
        $key = config('AES_token.key');
        $encrypted = openssl_encrypt($return, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
        die(base64_encode($encrypted));
    }else{
        die($return);
    }
}

/**
 * 返回成功信息代码
 * @author chenhan
 * @access public
 * @param  mixed  $data          提示信息或是数组
 * @param  int    $returncolla   判断返回参数是否需要加密：1加密，0不加密
 * @return string      返回数组
 **/
function putsuccess($data,$returncolla=0){
    $succ = array(
        1 => '操作成功！',
        2 => '注册成功',
        3 => '提交成功',
        4 => '图片保存成功',
        5 => '修改成功',
        6 => '开通成功',
        7 => '编辑成功',
        8 => '发布成功',
        9 => '保存成功',
        10 => '删除成功',
        11 => '回复成功'
    );
    //成功时，输出data数组
    if(is_array($data)){
        $res['status']=1;
        $res['msg'] = '操作成功';
        $res=array_merge($res,$data);
    }else{
        $res['status']=1;
        if(is_numeric($data)){
            $res['msg']=$succ[$data];
        }else{
            $res['msg']=$data;
        }
    }
    $return = json_encode($res,JSON_UNESCAPED_UNICODE);
    //判断是否需要加密
    if($returncolla == 1){
        $iv = config('AES_token.iv');
        $key = config('AES_token.key');
        $encrypted = openssl_encrypt($return, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
        die(base64_encode($encrypted));
    }else{
        die($return);
    }
}

/**
 * 生成订单
 * 主要用户订单的生成
 *
 * @return string        返回一个类似于1223143438859683的订单号
 */
function get_microtimes()
{
    list($usec, $sec) = explode(" ", microtime());

    return date("YmdHi", $sec) . substr($usec, 2, 4) . rand('1000', '9999');
}

/**
 * 接收数据
 * @access public|private|protected
 *
 * @param  array|string 提示信息或是数组
 *
 * @return array      返回数组
 **/
function info()
{
    $params = request()->param();
    return $params;
}

/**
 * 返回充值的商品的具体参数
 * @access public|private|protected
 *
 * @param  array|string 提示信息或是数组
 *
 * @return array      返回数组
 **/

function  Specific_parameters_commodities($goodsid){
    if(is_numeric($goodsid)){
        $json_string = file_get_contents(env('PLATFORM.BillingPoint'));
        $data = json_decode($json_string, true);
        foreach($data as $k=>$v){
            if($k == $goodsid){
                $results=$v;
            }
        }
        /*二维数组转化一维数组*/
        $result=array_reduce($results, 'array_merge', array());
        return $result;
    }

}

/**
 * 返回充值的商品的具体参数
 * @access public|private|protected
 *
 * @param  array|string 提示信息或是数组
 *
 * @return array     服务器B组 返回数组
 **/

function  Specific_parameters_commodities_server_B($goodsid){
    if(is_numeric($goodsid)){
        $json_string = file_get_contents(env('PLATFORM.BillingPoint'));
        $data = json_decode($json_string, true);
        foreach($data as $k=>$v){
            if($k == $goodsid){
                $results=$v;
            }
        }
        /*二维数组转化一维数组*/
        $result=array_reduce($results, 'array_merge', array());
        return $result;
    }
}
/*服务器处理 A服务器 newlogin.hemayouxi.cn  B组服务器 login.hemayouxi.cn */
function server_pay_order($extra='',$goods_id){
    $json =json_decode($extra,true);
    $server_ip=$json['serverip'];
    $good_configure_info=[];
    if(!empty($server_ip)){
        if($server_ip==config('GroupA_domain')){
            $good_configure_info=Specific_parameters_commodities($goods_id);
        }
        if($server_ip==config('GroupB_domain')){
            $good_configure_info=Specific_parameters_commodities_server_B($goods_id);
        }
    }else{
        $good_configure_info=Specific_parameters_commodities_server_B($goods_id);
    }
    return $good_configure_info;
}
/**
 * 返回道具详细信息
 * @access public|private|protected
 *
 * @param  array|string 提示信息或是数组
 *
 * @return array      返回数组
 **/
function  Specific_parameters_Recharge_channel($channel_id){
    if(is_numeric($channel_id)){
        $json_string = file_get_contents('../recharge.json');
        $data = json_decode($json_string, true);
        $results=[];
        foreach($data as $k=>$v){
            if($k == $channel_id){
                $results=$v;
            }
        }
        /*二维数组转化一维数组*/
        $result=array_reduce($results, 'array_merge', array());
        return $result;
    }
}
/**
 * 返回充值的商品的库存
 * @access public|private|protected
 *
 * @param  array|string 提示信息或是数组
 *
 * @return array      返回数组
 **/

function  Specific_parameters_commodities_ChargeStock($goodsid){
    if(is_numeric($goodsid)){
        $json_string = file_get_contents(env('PLATFORM.GoldStock'));
        $data = json_decode($json_string, true);
        $res = array_key_exists($goodsid,$data);
        if(!$res){
            $result=false;
        }else{
            foreach($data as $k=>$v){
                if($k == $goodsid){
                    $results=$v;
                }
            }
            $result=array_reduce($results, 'array_merge', array());
        }
        /*二维数组转化一维数组*/
        return $result;
    }

}
/**
 * 返回任务的具体参数
 * @access public|private|protected
 *
 * @param  array|string 提示信息或是数组
 *
 * @return array      返回数组
 **/

function  Specific_parameters_task($taskid){
    if(is_numeric($taskid)){
        $json_string = file_get_contents(env('PLATFORM.fish_task'));
        $data = json_decode($json_string, true);
        foreach($data as $k=>$v){
            if($k == $taskid){
                $results=$v;
            }
        }
        /*二维数组转化一维数组*/
        $result=array_reduce($results, 'array_merge', array());
        return $result;
    }

}

/**
 * 累计总充值对应相应vip等级
 * @access public|private|protected
 **/
function vip_level($total_recharge){
    $json_string = file_get_contents(env('PLATFORM.Vip'));
    $data = json_decode($json_string, true);
    $level=0;
    foreach($data as $k=>$v){
        if($total_recharge>=$v['Recharge']){
            $level++;
        }
    }
    return $level;
}
/**
 * 返回百度充值配置
 * @access public|private|protected
 *
 * @param  array|string 提示信息或是数组
 *
 * @return array      返回数组
 **/

function  BAIDU_GAME_RECHARGE_CONFIGGURATION($goodsid){
    if(is_numeric($goodsid)){
        $json_string = file_get_contents(env('PLATFORM.baidu'));
        $data = json_decode($json_string, true);
        $res = array_key_exists($goodsid,$data);
        if(!$res){
            $result=false;
        }else{
            foreach($data as $k=>$v){
                if($k == $goodsid){
                    $results=$v;
                }
            }
            $result=array_reduce($results, 'array_merge', array());
        }
        /*二维数组转化一维数组*/
        return $result;
    }
}
/**
 * 调用解析方法，将xml数据解析成对象
 * @access public|private|protected
 *
 * @param  array|string 提示信息或是数组
 *
 * @return array      返回数组
 **/

function xmlToObject($xmlStr) {
    if (!is_string($xmlStr) || empty($xmlStr)) {
        return false;
    }
    // 由于解析xml的时候，即使被解析的变量为空，依然不会报错，会返回一个空的对象，所以，我们这里做了处理，当被解析的变量不是字符串，或者该变量为空，直接返回false
    $postObj = simplexml_load_string($xmlStr, 'SimpleXMLElement', LIBXML_NOCDATA);
    $postObj = json_decode(json_encode($postObj),true);
    //将xml数据转换成对象返回
    return $postObj;
}

/**
 * 输出xml字符
 * @param $params 参数名称
 * return string 返回组装的xml
 **/
function data_to_xml($params){
    if(!is_array($params)|| count($params) <= 0)
    {
        return false;
    }
    $xml = "<xml>";
    foreach ($params as $key=>$val)
    {
        if (is_numeric($val)){
            $xml.="<".$key.">".$val."</".$key.">";
        }else{
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
    }
    $xml.="</xml>";
    return $xml;
}
/**
 * 输出xml字符
 * @param $params 微信签名
 * return string 返回组装的xml
 **/
function get_Sign($params){
    ksort($params);
    $string = '';
    foreach($params as $k => $v) {
        if($v != '' && $k != 'sign') {
            $string .= "{$k}={$v}&";
        }
    }
    $app_key = "HemaKeji02aJ7Hi0haJikowiNfVsEbhT";
    $sign = strtoupper(md5($string . "key={$app_key}"));
    return $sign;
}
function replyNotify_fail(){
    $data['return_code'] = 'FAIL';
    $data['return_msg'] = '';
    $xml = data_to_xml( $data );
    echo $xml;
    die();
}
function replyNotify_success(){
    $data['return_code'] = 'SUCCESS';
    $data['return_msg'] = 'OK';
    $xml = data_to_xml( $data );
    echo $xml;
    die();
}
/**
 * @author zhangzhiyuan
 * @version 2019-03-18
 * @param string  校验用户的合法性
 * @return string json
 */
function checkout_user_validity($userid){
    $Dbname = Db::connect('db_config2');
    $res = $Dbname->table('accounts_info')->where('UserID',$userid)->find();
    if(empty($res)){
        puterror('用户异常1001');
    }
}
/**
 * @author zhangzhiyuan
 * @version 2019-03-18
 * @param string  校验订单的合法性
 * @return string json
 */
function checkout_order_validity($userid,$time){
    $Dbname = Db::connect('db_config2');
    $order = $Dbname->table('tradelog')->where('userid',$userid)->where('createdat',$time)->find();
    if(!empty($order)){
        puterror('重复下单1001');
    }
}

/*异常处理*/
function Exception_handling_reporting_typeofget(){
        $time =date('Y-m-d H:i:s',time());
        $str ="<h1>Whitelabel Error Page</h1>
                This application has no explicit mapping for /error, so you are seeing this as a fallback.
                ".$time."</br>
                There was an unexpected error (type=Method Not Allowed, status=40001).</br>
                Request method 'GET' not supported";
        die($str);
}
/*参数缺失*/
function Exception_handling_reporting_typeofget_Missing(){
    $time =date('Y-m-d H:i:s',time());
    $str ="<h1>Whitelabel Error Page</h1>
                This application has no explicit mapping for /error, so you are seeing this as a fallback.
                ".$time."</br>
                There was an unexpected error (type=Method Not Allowed, status=40002).</br>
                Missing parameters";
    die($str);
}

/*抛出异常日志*/
function throw_Abnormal_Record_Log($logname,$information){
     file_put_contents($logname.'.txt', $information."\r\n", FILE_APPEND);
}

function curl_get($url, array $params = array(), $timeout = 5)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $file_contents = curl_exec($ch);
    curl_close($ch);
    return $file_contents;
}

/**
 * @author zhangzhiyuan
 * @version 2019-03-18
 * @param string  按参数名的ASCII码的增序排序
 * @return string json
 */
function getSignContent($params) {
    ksort ( $params );
    $stringToBeSigned = "";
    $i = 0;
    foreach ( $params as $k => $v ) {
        if (false === checkEmpty ( $v ) && "@" != substr ( $v, 0, 1 )) {
            if ($i == 0) {
                $stringToBeSigned .= "$k" . "=" . "$v";
            } else {
                $stringToBeSigned .= "&" . "$k" . "=" . "$v";
            }
            $i ++;
        }
    }
    return $stringToBeSigned;
}
/**
 * 校验$value是否非空
 *  if not set ,return true;
 *    if is null , return true;
 **/
 function checkEmpty($value) {
    if (!isset($value))
        return true;
    if ($value === null)
        return true;
    if (trim($value) === "")
        return true;

    return false;
}
/**
 *    VIVO HTTP请求发送
 *    if not set ,return true;
 *    if is null , return true;
 **/
function request_post($url = '', $param = '') {
    if (empty($url) || empty($param)) {
        return false;
    }
    $postUrl = $url;
    $curlPost = $param;
    $curl = curl_init();//初始化curl
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);//提交的参数
    $data = curl_exec($curl);//运行curl
    curl_close($curl);
    return $data;
}

/**
 *     M盟 平台 HTTP请求发送
 *    if not set ,return true;
 *    if is null , return true;
 **/
function do_request_post($url = '', $param = '') {
    if (empty($url) || empty($param)) {
        return false;
    }
    $headers = array(
        "Content-Type: application/json",
        "Content-Length: " . strlen($param) . "",
        "Accept: application/json",
    );
    $postUrl = $url;
    $curlPost = $param;
    $curl = curl_init();//初始化curl
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);//提交的参数
    $data = curl_exec($curl);//运行curl
    curl_close($curl);
    return $data;
}

function curl_post($url, array $query_data) {
    $post_str = http_build_query($query_data);
    $curl = curl_init(); // 初始化curl
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 显示输出结果
    curl_setopt($curl, CURLOPT_POST, 1); // post传输数据
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_str); // post传输数据
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 3); // 设置等待时间
    $header = array(
        "Content-Type: application/x-www-form-urlencoded; charset=UTF-8"
    );
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    //https 请求
    if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    $return_content = curl_exec($curl);
    curl_close($curl);
    return $return_content;
}

/**
     * 短信发送
     * @param $to    接收人
     * @param $model 短信模板ID
     * @param $code   短信验证码
     * @return json
     * @
     */
    function send_sms($to, $model, $code)
    {
        require_once '../extend/alisms/vendor/autoload.php';
        Config::load(); //加载区域结点配置
        $config = '根据你的实际情况读取配置文件或读取数据库，本项目是将配置写入数据库实现';
        $accessKeyId = 'LTAIuFOC03oi9x2t';
        $accessKeySecret = 'JoCwWrCm1OsH1HJ10xOOWJMHikNdrl';
        $templateParam = $code;
        //短信签名
        $signName = '河马游戏';
        //短信模板ID
        switch ($model) {
            case 1:
                $templateCode = 'SMS_168410170'; // 注册登录短信验证码模板
                break;
            case 2:
                $templateCode = $config['model_code_reset']; // 重置密码短信验证码模板
                break;
        }
        //短信API产品名（短信产品名固定，无需修改）
        $product = "Dysmsapi";
        //短信API产品域名（接口地址固定，无需修改）
        $domain = "dysmsapi.aliyuncs.com";
        //暂时不支持多Region（目前仅支持cn-hangzhou请勿修改）
        $region = "cn-hangzhou";
        // 初始化用户Profile实例
        $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
        // 增加服务结点
        DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
        // 初始化AcsClient用于发起请求
        $acsClient = new DefaultAcsClient($profile);
        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();
        // 必填，设置雉短信接收号码
        $request->setPhoneNumbers($to);
        // 必填，设置签名名称
        $request->setSignName($signName);
        // 必填，设置模板CODE
        $request->setTemplateCode($templateCode);
        // 可选，设置模板参数
        if ($templateParam) {
            $request->setTemplateParam(json_encode($templateParam));
        }
        //发起访问请求
        $acsResponse = $acsClient->getAcsResponse($request);
        //返回请求结果
        $result = json_decode(json_encode($acsResponse), true);
        // 具体返回值参考文档：https://help.aliyun.com/document_detail/55451.html?spm=a2c4g.11186623.6.563.YSe8FK
        return $result;
    }

// 自定义日志类型
function mylog($msg){
    trace($msg,'mylog');
}

// 调用服务器接口的日志
function serverLog($msg){
    trace($msg,'serverLog');
}

// 自定义广告日志类型
function adLog($msg){
    trace($msg,'adLog');
}

function set_cors(){
    $allows_origin = [
        "http://192.168.1.159:7456",
        "http://192.168.1.242:7070",
        "http://h5c.hemayouxi.cn",
        "https://h5c.hemayouxi.cn",
        "http://h5c.hemayouxi.com",
        "https://h5c.hemayouxi.com",
        "https://www.carcadefishing.com",
        "http://www.carcadefishing.com"
    ];
    $Origin = request()->header("Origin");
    if(in_array($Origin,$allows_origin)){
        header("Access-Control-Allow-Origin:{$Origin}");
        header("Access-Control-Allow-Methods:GET, POST");
    }
}
